package com.wangshupo.dewu.api;

import com.wangshupo.dewu.model.Result;
import com.wangshupo.dewu.model.User;
import com.wangshupo.dewu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wangshupo
 */
@Controller
@RequestMapping("/api/user")
public class UserAPI {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param userName
     * @param pwd
     * @return
     */
    @PostMapping("/reg")
    @ResponseBody
    public Result<User> reg(@RequestParam("userName") String userName, @RequestParam("pwd") String pwd) {
        return userService.register(userName, pwd);
    }

    /**
     * 用户登录
     * @param userName
     * @param pwd
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result<User> login(@RequestParam("userName") String userName, @RequestParam("pwd") String pwd, HttpServletRequest request) {
        Result<User> result = userService.login(userName, pwd);

        if (result.isSuccess()) {
            request.getSession().setAttribute("userId", result.getData().getId());  //添加 session值
        }

        return result;
    }

    /**
     * 用户退出
     * @param request
     * @return
     */

    @GetMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request) {
        Result result = new Result();
        request.getSession().removeAttribute("userId");  //移除 session值

        result.setSuccess(true);
        return result;
    }

    @GetMapping("/toLogin")
    @ResponseBody
    public Result toLogin() {
        Result result = new Result();
        result.setMessage("请用户先登录");
        return result;
    }

}
